import { readFileSync, writeFileSync } from 'node:fs'
import { dirname, join, relative } from 'node:path/posix'
import { PROJECT_ROOT } from './PROJECT_ROOT.ts'
import { findFilesByName } from './findFilesByName.ts'

export const ensureTsReferences = (options: { fix?: boolean } = {}) => {
  const { fix = false } = options

  const tsconfigs = findFilesByName({
    name: 'tsconfig.json',
    cwd: join(PROJECT_ROOT, 'packages'),
  })

  const tsconfigPath = join(PROJECT_ROOT, 'tsconfig.json')
  const currentContent = readFileSync(tsconfigPath, 'utf-8')
  const currentConfig = JSON.parse(currentContent)

  const expectedConfig = {
    ...currentConfig,
    references: [
      ...tsconfigs.map((tsconfig) => ({
        path: `./${relative(PROJECT_ROOT, dirname(tsconfig))}`,
      })),
    ],
  }

  const expectedReferences = JSON.stringify(expectedConfig.references)
  const currentReferences = JSON.stringify(currentConfig.references)

  if (expectedReferences !== currentReferences) {
    if (fix) {
      writeFileSync(tsconfigPath, JSON.stringify(expectedConfig))
      console.log('✅ Fixed tsconfig.json references')
    } else {
      console.error('❌ tsconfig.json references are incorrect')
      console.error('\nExpected references:', expectedConfig.references)
      console.error('\nCurrent references:', currentConfig.references)
      process.exit(1)
    }
  } else {
    console.log('✓ tsconfig.json references are correct')
  }
}
